package cn.chair.controller.admin;

import cn.chair.annotation.PublicApi;
import cn.chair.dao.WebPackageDao;
import cn.chair.entity.WebPackage;
import cn.chair.util.SmallUtil;
import life.innovation.builder.SqlBuilder;
import life.innovation.exception.DataWriteException;
import life.innovation.exception.ResourceNotFoundException;
import life.innovation.exception.UnauthorizedException;
import life.innovation.model.BaseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping(value="package")
@RestController
public class WebPackageController extends BaseModel{

    @Autowired
    @Lazy
    private WebPackageDao webPackageDao;
    @CrossOrigin(origins="http://beta.api.admin.momole.com")
    @PostMapping(value="getPackages")
    public List<WebPackage> getWebPackages(){
        return webPackageDao.find(SqlBuilder.init());
    }

    @GetMapping(value="{id}")
    public WebPackage get(@PathVariable int id) throws ResourceNotFoundException {

        WebPackage webPackage = webPackageDao.findOne(SqlBuilder.init().where("id",id));
        if(webPackage == null){
            throw new ResourceNotFoundException("error banner missing");

        }

        webPackage.setAmount(webPackage.getAmount().replace("元",""));
        webPackage.setTime(webPackage.getTime().replace("分钟",""));

        return webPackage;
    }

    @GetMapping(value = "updatePackage/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void get(HttpServletRequest request,
                    @PathVariable int id,
                    @RequestParam String name,
                    @RequestParam String amount,
                    @RequestParam String time) throws ResourceNotFoundException, DataWriteException, UnauthorizedException {
        WebPackage webPackage = webPackageDao.findOne(SqlBuilder.init().where("id",id));
        if(webPackage == null){
            throw new ResourceNotFoundException("error banner missing");
        }
        webPackage.setName(name);
        webPackage.setAmount(amount+"元");
        webPackage.setTime(time+"分钟");
        webPackageDao.update(webPackage);
    }

}
